
from django.shortcuts import render

from rest_framework.response import Response

from rest_framework.views import APIView

from QQLoginTool.QQtool import OAuthQQ

from mall.mall import settings


from rest_framework.generics import GenericAPIView
from .serializers import OauthQQUserSerializer
# Create your views here.
from oauth.models import OAuthQQUser

from oauth.utils import generate_openid_token


class QQauthQQAPIView(APIView):

    def get(self,request):
        # 从哪个页面进来，将来登录成功后，会自动回到那个页面
        state=request.query_params.get('state')
        if not state:
            state='/'

        #获取QQ登录的页面网址

        oauth=OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                      client_secret=settings.QQ_CLIENT_SECRET,
                      redirect_uri=settings.QQREDIRECT_URI,
                      state=state)

        auth_url=oauth.get_qq_url()
        return Response({"auth_url":auth_url})



from rest_framework import status

class OauthQQUserAPIView(APIView):

    def get(self,request):
        # 接收code
        code=request.query_params.get('code')
        # 通过code获取token
        if not code:

            return Response(status=status.HTTP_400_BAD_REQUEST)

        oauth=OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                      client_secret=settings.QQ_CLIENT_SECRET,
                      redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            token=oauth.get_access_token(code)
            openid=oauth.get_open_id(token)

        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        try:
            qquser=OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            openid_itsdangerous=generate_openid_token(openid)
            return Response({'access_token':openid_itsdangerous})
        else:
            from rest_framework_jwt.settings import api_settings

            jwt_payload_handler=api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler=api_settings.JWT_ENCODE_HANDLER

            payload=jwt_payload_handler(qquser.user)
            token=jwt_encode_handler(payload)

            return Response({
                'token':token,
                'username':qquser.user.username,
                'user_id':qquser.user.id
            })

    def post(self,request):
        # 接收数据
        data=request.data
        # 校验数据（access_token,短信验证码，判断用户是否存在）
        serializer=OauthQQUserSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        qquser=serializer.save()

        # 绑定完，应该自动登录
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler=api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler=api_settings.JWT_ENCODE_HANDLER

        payload=jwt_payload_handler(qquser.user)
        token=jwt_encode_handler(payload)

        return Response({
            'token':token,
            'username':qquser.user.username,
            'user_id':qquser.user.id
        })




# 哈哈哈哈哈哈哈哈哈哈
#####################itsdangerous#####################################

from mall.mall import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serislizer
s=Serislizer(serializer=settings.SECRET_KEY,expires_in=3600)
data={
    'openid':'1234567890'
}

token=s.dumps(data)

s=Serislizer(secret_key=settings.SECRET_KEY,expires_in=3600)
s.loads(token)

s=Serislizer(secret_key=settings.SECRET_KEY,expires_in=1)

data={
    'openid':'1234567890'
}
token=s.dumps(data)